//
// Created by DengLibin on 2018/12/8 0008.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//字符串转数字
int str_to_num(char *str)
{
    char *p = str;
    int num = 0; //计算有多少位
    while (*p != '\0')
    {
        int c = *p;
        if (c < '0' || c > '9')
        {
            printf("含有非法字符\n");
            return -1;
        }
        num++;
        p++;
    }

    p = str;
    int sum = 0;
    for (; num > 0; num--)
    {
        //计算j的值 1,10,100,1000...(权值)
        int j = 1;
        for (int i = 0; i < num - 1; i++)
        {
            j *= 10;
        }
        sum += ((*p - '0') * j);
        p++;
    }
    return sum;
}
int str_to_num_2(char *str)
{
    size_t len = strlen(str);
    if (len == 0)
    {
        return 0;
    }
    int num = 0;
    size_t index = 0;
    int flag = 1;
    if (str[0] == '-')
    {
        index = 1;
        flag = 0;
    }
    while (index < len)
    {
        num *= 10;
        if (str[index] < '0' || str[index] > '9')
        {
            printf("有非法字符\n");
            exit(1);
        }
        num += (int)(str[index] - '0');
        index++;
    }
    return flag ? num : -num;
}
int main2(int argc, char *argv[])
{
    printf("请输入数字字符串:\n");
    char s[1024];
    gets(s); // scanf遇到空格和tab符号认为是结束符，gets认为回车是结束符
    // int num = str_to_num(s);
    int num = str_to_num_2(s);
    printf("转成数字:%d\n", num);
    return 0;
}
